package com.kurt.interceptor;

import com.kurt.util.JwtUtil;
import com.kurt.util.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * JWT拦截器
 * 从请求头中提取JWT token，解析用户信息并设置到UserContext中
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtInterceptor implements HandlerInterceptor {

    private final JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            // 从请求头中获取Authorization
            String authHeader = request.getHeader("Authorization");
            if (authHeader != null && authHeader.startsWith("Bearer ")) {
                String token = authHeader.substring(7);

                // 解析token获取用户信息
                if (jwtUtil.validateToken(token)) {
                    Long userId = jwtUtil.getUserIdFromToken(token);
                    String username = jwtUtil.getUsernameFromToken(token);
                    Long organizationId = jwtUtil.getOrganizationIdFromToken(token);

                    // 设置用户上下文
                    UserContext.setUserContext(userId, username, organizationId);

                    log.debug("用户上下文已设置: {}", UserContext.getUserContextInfo());
                } else {
                    log.warn("无效的JWT token: {}", token);
                }
            } else {
                log.debug("请求头中未找到Authorization或格式不正确");
            }
        } catch (Exception e) {
            log.error("JWT拦截器处理异常", e);
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完成后清除用户上下文，防止内存泄漏
        UserContext.clear();
    }
}
